package com.hunan.api.catv.mq.consumer;

import com.hunan.api.catv.common.CacheName;
import com.hunan.api.catv.entity.po.News;
import com.hunan.api.catv.entity.vo.NewsVo;
import com.hunan.api.catv.service.biz.news.NewsBiz;
import com.hunan.api.catv.service.impl.tencent_cloud.vm.VmService;
import com.hunan.api.catv.utils.GsonUtils;
import com.hunan.api.catv.utils.RedisUtils;
import com.tencentcloudapi.vm.v20200709.models.CreateVideoModerationTaskResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.Date;

/**
 * 用户发布短视频
 *
 * @Author: wangchao
 * @Date: 2021/1/7 9:53
 */
@Component
@Slf4j
public class ReleaseVedioConsumer {

    @Autowired
    NewsBiz newsBiz;

    @Autowired
    RedisUtils redisUtils;

    private final VmService vmService;

    public ReleaseVedioConsumer(VmService vmService) {
        this.vmService = vmService;
    }


    //@RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConstants.RELEASE_VEDIO_QUEUE, durable = "true"), exchange = @Exchange(value = MqConstants.RELEASE_VEDIO_EXCHANGE, durable = "true", type = "topic"), key = MqConstants.RELEASE_VEDIO_ROUTINGKEY))
    @Transactional(rollbackFor = Exception.class)
    public void tasks(String msg) {
        log.info("[用户发布短视频:{}]", msg);
        NewsVo newsVo = GsonUtils.fromJson(msg, NewsVo.class);
        String[] vedioUrls = newsVo.getUrl().split(":");
        String newUrls = vedioUrls[2] + ":" + vedioUrls[3].split(",")[0];
        Integer newsId = newsVo.getNewsId();
        boolean flag = false;
        News news = null;
        try {
            CreateVideoModerationTaskResponse videoModerationTask = vmService.createVideoModerationTask(newUrls.substring(1, newUrls.length() - 1), String.valueOf(newsId));
            if (videoModerationTask != null && videoModerationTask.getResults() != null) {
                news = new News().selectById(newsId);
                if (news != null) {
                    flag = news.setReviewId(videoModerationTask.getResults()[0].getTaskId()).setAuditResultsType(2)
                            .updateById();
                }
            } else {
                //人工审核
                news = new News().selectById(newsId);
                if (news != null) {
                    flag = news.setState(6).setReleaseTime(new Date()).updateById();
                }
            }
            if (flag) {
                //短视频信息存入缓存
                redisUtils.del(MessageFormat.format(CacheName.getNewsInfo, String.valueOf(news.getNewsId())));
                NewsVo newsInfo = newsBiz.getNewsInfo(newsId);
            }
            log.info("用户发布视频审核修改结果:{}", flag);
        } catch (Exception e) {
            log.error("[用户发布视频审核失败:{}]", e);
        }
    }
}
